#include "textfield.hpp"

#include "sdlutil.hpp"

TextField::TextField(IElement* parent, 
		     SDL_Surface* surf, 
		     FontMap* fmap)
  :IElement(parent, surf)
  ,fMap_(fmap)
{
}

TextField::~TextField()
{
}

void TextField::SetBuffer(TextBuffer* buf)
{
	buffer_ = buf;
}

void TextField::update()
{

}

void TextField::render(int x, int y)
{
	int vert_shift = 20 + y;
	for(int i = 0;i<10;i++)
	{
		std::string * cs = buffer_->GetLine(i);
		if(cs != NULL)
		{						
			vert_shift += 20 + sc_ver_space + 
				drawString(x, vert_shift, cs);
		}
	}
}

int TextField::drawChar(int x, int y, unsigned char ch)
{
	FontChar_P buf = fMap_->getChar(ch);

  for(int lx = 0; lx< buf->height; lx++)
    {
      for(int ly = 0; ly< buf->width; ly++)
	{
	  if(buf->data_[ly + lx*buf->width] > 0)
	    {
	      uint cl = buf->data_[ly + lx*buf->width];
	      cl |= cl << 8;
	      cl |= cl << 24;
	      
	      set_pixel(surface_, x+ly, y+lx-buf->top, 
			cl);
	    }
	  else
	    {
	      set_pixel(surface_, x+ly, y+lx-buf->top, 
			0x00000000);
	    } 

	}
    }
  return buf->width;	
}

int TextField::drawString(int x, int y, std::string * str)
{
	 int cur_shift = 0;
  int y_shift = 0;
  for(int i = 0; i< str->length(); i++)
    {
      unsigned char cur_ch = str->at(i);
      if(cur_ch == ' ')
	{
	  cur_shift += sc_space_size;
	}
      else if(cur_ch == '\n')
	{
	  y_shift += 20 + sc_ver_space;
	  cur_shift = 0;
	}
      else if(isgraph(cur_ch))
	{
	  cur_shift += sc_hor_space + 
	    drawChar( x+cur_shift, 
		      y+y_shift,
		      cur_ch);
	}
    }
	return y_shift;
}
